package com.his.his_system.controller.VisitController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.his.his_system.domain.DzmHisCarePkg;
import com.his.his_system.domain.DzmHisRegistration;
import com.his.his_system.mapper.DefaultMapper;
import com.his.his_system.service.DzmHisCarePkgService;
import com.his.his_system.service.DzmHisRegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 定时任务
 */
@Component
@EnableScheduling
@Slf4j
public class Query {

    @Resource
    private DefaultMapper defaultMapper;

    @Resource
    private DzmHisRegistrationService dzmHisRegistrationService;

    @Resource
    private DzmHisCarePkgService dzmHisCarePkgService;

    @Scheduled(cron = "59 59 23 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void myTask() {
        log.info("开始执行了定时任务");
        List<DzmHisRegistration> reglist= defaultMapper.getAlreadyReg();
        for(DzmHisRegistration re : reglist){
            Long rid = re.getRegistrationId();
            UpdateWrapper<DzmHisRegistration> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("registration_id",rid)
                    .set("registration_status",4)
                    .set("update_time",(int)(System.currentTimeMillis()/1000));
            if(!dzmHisRegistrationService.update(updateWrapper)) {
                log.error("修改挂号表为作废失败");
                throw new RuntimeException("修改失败");
            }
        }
        log.info("定时任务执行成功");
    }

    @PostConstruct
    public void init() {
        log.info("定时任务执行成功");
        List<DzmHisRegistration> reglist= defaultMapper.getAlreadyReg();
        for(DzmHisRegistration re : reglist){
            Long rid = re.getRegistrationId();
            UpdateWrapper<DzmHisRegistration> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("registration_id",rid)
                    .set("registration_status",4)
                    .set("update_time",(int)(System.currentTimeMillis()/1000));
            if(!dzmHisRegistrationService.update(updateWrapper)) {
                log.error("修改挂号表为作废失败");
                throw new RuntimeException("修改失败");
            }
        }
        log.info("定时任务执行成功");
    }
}
